/*
 * Copyright (C) 2013 Sony Computer Entertainment Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

#include "config.h"

#if ENABLE(VIDEO)
#include "MediaPlayerPrivateManx.h"

#include "ContentType.h"
#include "FocusController.h"
#include "FrameView.h"
#include "GraphicsContext.h"
#include "HTMLMediaElement.h"
#include "HTMLNames.h"
#include "HTMLSourceElement.h"
#include "HTMLTrackElement.h"
#include "NotImplemented.h"
#include "Page.h"
#include "PageVisibilityState.h"
#include "PlatformContextCairo.h"

#include <wtf/text/CString.h>

#if USE(ACCELERATED_COMPOSITING)
#include "Settings.h"
#endif

#ifdef USE_SELF_TIMER
#define SELF_TIMER_INTERVAL (1.0 / 60.0)
#endif

// #define TRACE_FUNCTION printf("[WebCore::MediaPlayerPrivate] %s\n", __FUNCTION__)
#define TRACE_FUNCTION

namespace WebCore {

void MediaPlayerPrivate::registerMediaEngine(MediaEngineRegistrar registrar)
{
    TRACE_FUNCTION;
    registrar(create, getSupportedTypes, supportsType, 0, 0, 0);
}

PassOwnPtr<MediaPlayerPrivateInterface> MediaPlayerPrivate::create(MediaPlayer* player)
{
    TRACE_FUNCTION;
    return adoptPtr(new MediaPlayerPrivate(player));
}

void MediaPlayerPrivate::getSupportedTypes(HashSet<String>& types)
{
    TRACE_FUNCTION;
    notImplemented();
}

MediaPlayer::SupportsType MediaPlayerPrivate::supportsType(const String& type, const String& codecs, const KURL&)
{
    TRACE_FUNCTION;
    if (type.isNull() || type.isEmpty())
        return MediaPlayer::IsNotSupported;

    if (!type.startsWith("audio/") && !type.startsWith("video/") && !type.startsWith("application/"))
        return MediaPlayer::IsNotSupported;

    int codecCheck = Manx::MediaPlayer::supportsType(type.utf8().data(), codecs.ascii().data());
    if (codecCheck == Manx::MediaPlayer::PLAYABLE_STATUS_PROBABLY)
        return MediaPlayer::IsSupported;
    if (codecCheck == Manx::MediaPlayer::PLAYABLE_STATUS_MAYBE)
        return MediaPlayer::MayBeSupported;

    return MediaPlayer::IsNotSupported;
}

bool MediaPlayerPrivate::isAvailable()
{
    TRACE_FUNCTION;
    notImplemented();
    return true;
}

MediaPlayerPrivate::MediaPlayerPrivate(MediaPlayer* player)
    : m_player(player)
    , m_platformMediaPlayer(0)
#ifdef USE_SELF_TIMER
    , m_timer(adoptPtr(new Timer<MediaPlayerPrivate>(this, &MediaPlayerPrivate::timerFired)))
#endif
{
    TRACE_FUNCTION;
    // m_platformMediaPlayer = new Manx::MediaPlayer(this);
    m_platformMediaPlayer = Manx::MediaPlayer::create(this);

#ifdef USE_SELF_TIMER
    m_timer->startRepeating(SELF_TIMER_INTERVAL);
#endif
}

MediaPlayerPrivate::~MediaPlayerPrivate()
{
    TRACE_FUNCTION;
#ifdef USE_SELF_TIMER
    m_timer->stop();
#endif
    delete m_platformMediaPlayer;
}

#ifdef USE_SELF_TIMER
void MediaPlayerPrivate::timerFired(Timer<MediaPlayerPrivate>* timer)
{
    TRACE_FUNCTION;

#if OS(PSP2)
    if (hasVideo() && !m_platformMediaPlayer->paused()) {
        HTMLMediaElement * videoElement = (HTMLMediaElement*)m_player->mediaPlayerClient();
        if (videoElement)
            videoElement->pause();
    }
#endif

    m_platformMediaPlayer->update(timer->repeatInterval());
}
#endif

void MediaPlayerPrivate::load(const String& url)
{
    TRACE_FUNCTION;

    m_player->characteristicChanged();

#if OS(ORBIS)
    HTMLMediaElement* element = static_cast<HTMLMediaElement*>(m_player->mediaPlayerClient());
    if (element) {
        m_platformMediaPlayer->setMuted(element->muted());
        m_platformMediaPlayer->setVolume(element->volume());
    }
#endif

    ContentType type = ContentType(mediaSourceTypeStringForUrl(url));
    DEFINE_STATIC_LOCAL(const String, codecs, ("codecs"));
    m_platformMediaPlayer->load(url.utf8().data(), type.type().lower().utf8().data(), type.parameter(codecs).utf8().data());
}

void MediaPlayerPrivate::cancelLoad()
{
    TRACE_FUNCTION;
    m_platformMediaPlayer->cancelLoad();
}

void MediaPlayerPrivate::prepareToPlay()
{
    TRACE_FUNCTION;
    m_platformMediaPlayer->prepareToPlay();
}

#if USE(ACCELERATED_COMPOSITING)
PlatformLayer* MediaPlayerPrivate::platformLayer() const
{
    return (PlatformLayer*)&m_platformLayer;
}
#endif // USE(ACCELERATED_COMPOSITING)

void MediaPlayerPrivate::play()
{
    TRACE_FUNCTION;
#if ENABLE(VIDEO_TRACK)
    setTracks();
#endif

#if OS(PSP2)
    Document* document = m_player->mediaPlayerClient()->mediaPlayerOwningDocument();
    if (document && document->processingLoadEvent())
        return;
#endif
    m_platformMediaPlayer->play();
}

void MediaPlayerPrivate::pause()
{
    TRACE_FUNCTION;
    m_platformMediaPlayer->pause();
}

bool MediaPlayerPrivate::supportsFullscreen() const
{
    return true;
}

IntSize MediaPlayerPrivate::naturalSize() const
{
    TRACE_FUNCTION;
    int width = 0;
    int height = 0;
    m_platformMediaPlayer->naturalSize(width, height);
    return IntSize(width, height);
}

bool MediaPlayerPrivate::hasVideo() const
{
    TRACE_FUNCTION;
    return m_platformMediaPlayer->hasVideo();
}

bool MediaPlayerPrivate::hasAudio() const
{
    TRACE_FUNCTION;
    return m_platformMediaPlayer->hasAudio();
}

void MediaPlayerPrivate::setVisible(bool visible)
{
    TRACE_FUNCTION;
    m_platformMediaPlayer->setVisible(visible);
}

float MediaPlayerPrivate::duration() const
{
    TRACE_FUNCTION;
    return m_platformMediaPlayer->duration();
}

float MediaPlayerPrivate::currentTime() const
{
    TRACE_FUNCTION;
    return m_platformMediaPlayer->currentTime();
}

void MediaPlayerPrivate::seek(float time)
{
    TRACE_FUNCTION;
    m_platformMediaPlayer->seek(time);
}

bool MediaPlayerPrivate::seeking() const
{
    TRACE_FUNCTION;
    return m_platformMediaPlayer->seeking();
}

void MediaPlayerPrivate::setRate(float rate)
{
    TRACE_FUNCTION;
    m_platformMediaPlayer->setRate(rate);
}

bool MediaPlayerPrivate::paused() const
{
    TRACE_FUNCTION;
    return m_platformMediaPlayer->paused();
}

void MediaPlayerPrivate::setVolume(float volume)
{
    TRACE_FUNCTION;
    m_platformMediaPlayer->setVolume(volume);
}

bool MediaPlayerPrivate::supportsMuting() const
{
    TRACE_FUNCTION;
    return m_platformMediaPlayer->supportsMuting();
}

void MediaPlayerPrivate::setMuted(bool muted)
{
    TRACE_FUNCTION;
    m_platformMediaPlayer->setMuted(muted);
}

MediaPlayer::NetworkState MediaPlayerPrivate::networkState() const
{
    TRACE_FUNCTION;
    MediaPlayer::NetworkState networkState = MediaPlayer::Empty;
    switch (m_platformMediaPlayer->networkState()) {
    case Manx::MediaPlayer::Empty:
        networkState = MediaPlayer::Empty;
        break;
    case Manx::MediaPlayer::Idle:
        networkState = MediaPlayer::Idle;
        break;
    case Manx::MediaPlayer::Loading:
        networkState = MediaPlayer::Loading;
        break;
    case Manx::MediaPlayer::Loaded:
        networkState = MediaPlayer::Loaded;
        break;
    case Manx::MediaPlayer::FormatError:
        networkState = MediaPlayer::FormatError;
        break;
    case Manx::MediaPlayer::NetworkError:
        networkState = MediaPlayer::NetworkError;
        break;
    case Manx::MediaPlayer::DecodeError:
        networkState = MediaPlayer::DecodeError;
        break;
    }
    return networkState;
}

MediaPlayer::ReadyState MediaPlayerPrivate::readyState() const
{
    TRACE_FUNCTION;
    MediaPlayer::ReadyState readyState = MediaPlayer::HaveNothing;
    switch (m_platformMediaPlayer->readyState()) {
    case Manx::MediaPlayer::HaveNothing:
        readyState = MediaPlayer::HaveNothing;
        break;
    case Manx::MediaPlayer::HaveMetadata:
        readyState = MediaPlayer::HaveMetadata;
        break;
    case Manx::MediaPlayer::HaveCurrentData:
        readyState = MediaPlayer::HaveCurrentData;
        break;
    case Manx::MediaPlayer::HaveFutureData:
        readyState = MediaPlayer::HaveFutureData;
        break;
    case Manx::MediaPlayer::HaveEnoughData:
        readyState = MediaPlayer::HaveEnoughData;
        break;
    }
    return readyState;
}

float MediaPlayerPrivate::maxTimeSeekable() const
{
    TRACE_FUNCTION;
    return m_platformMediaPlayer->maxTimeSeekable();
}

double MediaPlayerPrivate::minTimeSeekable() const
{
    TRACE_FUNCTION;
    return m_platformMediaPlayer->minTimeSeekable();
}

PassRefPtr<TimeRanges> MediaPlayerPrivate::buffered() const
{
    TRACE_FUNCTION;
    float start = 0.0;
    float end = 0.0;
    RefPtr<TimeRanges> timeRanges = TimeRanges::create();

    m_platformMediaPlayer->buffered(start, end);
    if (start >= 0.0 && end >= 0.0)
        timeRanges->add(start, end);
    return timeRanges.release();
}

bool MediaPlayerPrivate::didLoadingProgress() const
{
    TRACE_FUNCTION;
    return m_platformMediaPlayer->didLoadingProgress();
}

void MediaPlayerPrivate::setSize(const IntSize& size)
{
    TRACE_FUNCTION;
    m_platformMediaPlayer->setSize(size.width(), size.height());
}


    //
    // TODO:
    //
    // GraphicsContext contains not only the video element but also other elements that should be repaited.
    // However, the another rect parameter always points the position of video element in View.
    // We should move paintRect with some other offset value to get the actual rect of video element in Manx::MediaPlayer.
    //
    // paintRect.moveBy(...);
    //

void MediaPlayerPrivate::paint(GraphicsContext* context, const IntRect& rect)
{
    TRACE_FUNCTION;

    if (context->paintingDisabled())
        return;

#if !USE(ACCELERATED_COMPOSITING)
    HTMLMediaElement* element = static_cast<HTMLMediaElement*>(m_player->mediaPlayerClient());
    IntRect frameRect = element->document()->view()->windowClipRect();
    IntRect drawRect = rect;
    drawRect.moveBy(frameRect.location());
    IntRect invalid;
    element->document()->view()->invalidateRect(invalid);
    
    IntRect paintRect(IntPoint(0, 0), IntSize(rect.width(), rect.height()));

//    m_platformMediaPlayer->paint(cr, drawRect.x(), drawRect.y(), drawRect.width(), drawRect.height());
#if OS(PSP2)
    PlatformContextCairo* cairo = context->platformContext();
    cairo_t* cr = cairo->cr();

    cairo_save(cr);
    cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
    cairo_rectangle(cr, drawRect.x(), drawRect.y(), drawRect.width(), drawRect.height());
    cairo_fill(cr);
    cairo_restore(cr);
#endif
#endif
}

void MediaPlayerPrivate::setPreload(MediaPlayer::Preload preload)
{
    TRACE_FUNCTION;

    Manx::MediaPlayer::Preload manxPreload = Manx::MediaPlayer::Auto;
    switch (preload) {
    case MediaPlayer::None:
        manxPreload = Manx::MediaPlayer::None;
        break;
    case MediaPlayer::MetaData:
        manxPreload = Manx::MediaPlayer::MetaData;
        break;
    case MediaPlayer::Auto:
        manxPreload = Manx::MediaPlayer::Auto;
        break;
    }
    m_platformMediaPlayer->setPreload(manxPreload);
}

#if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
void MediaPlayerPrivate::deliverNotification(MediaPlayerProxyNotificationType)
{
    TRACE_FUNCTION;
    notImplemented();
}

void MediaPlayerPrivate::setMediaPlayerProxy(WebMediaPlayerProxy*)
{
    TRACE_FUNCTION;
    notImplemented();
}
#endif

#if USE(ACCELERATED_COMPOSITING)
bool MediaPlayerPrivate::supportsAcceleratedRendering() const
{
    return true;
}

void MediaPlayerPrivate::acceleratedRenderingStateChanged()
{
    m_player->mediaPlayerClient()->mediaPlayerRenderingModeChanged(m_player);
}
#endif // USE(ACCELERATED_COMPOSITING)

MediaPlayer::MovieLoadType MediaPlayerPrivate::movieLoadType() const
{
    TRACE_FUNCTION;

    MediaPlayer::MovieLoadType movieLoadType = MediaPlayer::Unknown;

    switch (m_platformMediaPlayer->movieLoadType()) {
    case Manx::MediaPlayer::Unknown:
        movieLoadType = MediaPlayer::Unknown;
        break;
    case Manx::MediaPlayer::Download:
        movieLoadType = MediaPlayer::Download;
        break;
    case Manx::MediaPlayer::StoredStream:
        movieLoadType = MediaPlayer::StoredStream;
        break;
    case Manx::MediaPlayer::LiveStream:
        movieLoadType = MediaPlayer::LiveStream;
        break;
    }

    return movieLoadType;
}

bool MediaPlayerPrivate::hasSingleSecurityOrigin() const
{
    TRACE_FUNCTION;
    return true;
}

#if ENABLE(MANX_CANVAS_COMPOSITING)
uint32_t MediaPlayerPrivate::canvasHandle() const
{
    return m_platformLayer.canvasHandle();
}
#endif

#if OS(ORBIS)
void MediaPlayerPrivate::restoreReleasedResource()
{
    m_platformMediaPlayer->restoreReleasedResource();
}
#endif

void MediaPlayerPrivate::mediaPlayerNetworkStateChanged()
{
    TRACE_FUNCTION;
    m_player->networkStateChanged();
}

void MediaPlayerPrivate::mediaPlayerReadyStateChanged()
{
    TRACE_FUNCTION;
    m_player->readyStateChanged();
}

void MediaPlayerPrivate::mediaPlayerVolumeChanged(float volume)
{
    TRACE_FUNCTION;
    m_player->volumeChanged(volume);
}

void MediaPlayerPrivate::mediaPlayerMuteChanged(bool mute)
{
    TRACE_FUNCTION;
    m_player->muteChanged(mute);
}

void MediaPlayerPrivate::mediaPlayerTimeChanged()
{
    TRACE_FUNCTION;
    m_player->timeChanged();
}

void MediaPlayerPrivate::mediaPlayerDurationChanged()
{
    TRACE_FUNCTION;
    m_player->durationChanged();
}

void MediaPlayerPrivate::mediaPlayerRateChanged()
{
    TRACE_FUNCTION;
    m_player->rateChanged();
}

void MediaPlayerPrivate::mediaPlayerPlaybackStateChanged()
{
    TRACE_FUNCTION;
    m_player->playbackStateChanged();
}

void MediaPlayerPrivate::mediaPlayerRepaint()
{
    TRACE_FUNCTION;
    m_player->repaint();
}

void MediaPlayerPrivate::mediaPlayerSizeChanged()
{
    TRACE_FUNCTION;
    m_player->sizeChanged();
}

void MediaPlayerPrivate::mediaPlayerEngineUpdated()
{
    TRACE_FUNCTION;

    WebCore::MediaPlayerClient* client = m_player->mediaPlayerClient();
    if (client)
        client->mediaPlayerEngineUpdated(m_player);
}

void MediaPlayerPrivate::mediaPlayerFirstVideoFrameAvailable()
{
    TRACE_FUNCTION;
    m_player->firstVideoFrameAvailable();
}

void MediaPlayerPrivate::mediaPlayerCharacteristicChanged()
{
    TRACE_FUNCTION;
    m_player->characteristicChanged();
}

void MediaPlayerPrivate::mediaPlayerUpdateCanvasHandle(bool isCanvasMode, uint32_t canvasHandle)
{
#if USE(ACCELERATED_COMPOSITING) && USE(TEXTURE_MAPPER) && USE(TEXTURE_MAPPER_GL)
    m_platformLayer.updateCanvasHandle(isCanvasMode, canvasHandle);
#endif
}

bool MediaPlayerPrivate::mediaPlayerIsPaused() const
{
    TRACE_FUNCTION;

    WebCore::MediaPlayerClient* client = m_player->mediaPlayerClient();
    if (client)
        return client->mediaPlayerIsPaused();
    return true;
}

bool MediaPlayerPrivate::mediaPlayerAcceleratedCompositingEnabled()
{
#if USE(ACCELERATED_COMPOSITING)
    Document* document = m_player->mediaPlayerClient()->mediaPlayerOwningDocument(); 
    if (document && document->settings())
        return document->settings()->acceleratedCompositingEnabled();
#endif
    return false;
}

bool MediaPlayerPrivate::mediaPlayerIsActive() const
{
    Document* document = m_player->mediaPlayerClient()->mediaPlayerOwningDocument(); 
    if (document && document->page() && document->page()->focusController())
        return document->page()->focusController()->isActive();
    return false;
}

bool MediaPlayerPrivate::mediaPlayerIsVisible() const
{
#if ENABLE(PAGE_VISIBILITY_API)
    Document* document = m_player->mediaPlayerClient()->mediaPlayerOwningDocument(); 
    if (document && document->page() && document->page()->focusController())
        return (document->page()->visibilityState() == PageVisibilityStateVisible);
#endif
    return false;
}

const String& MediaPlayerPrivate::mediaSourceTypeStringForUrl(const String& url)
{
    HTMLMediaElement* element = static_cast<HTMLMediaElement*>(m_player->mediaPlayerClient());
    for (Node* node = element->firstChild(); node; node = node->nextSibling()) {
        if (node->hasTagName(HTMLNames::sourceTag)) {
            HTMLSourceElement* source = static_cast<HTMLSourceElement*>(node);
            if (source->getNonEmptyURLAttribute(HTMLNames::srcAttr).string().startsWith(url))
                return source->getAttribute(HTMLNames::typeAttr).string();
        }
    }
    DEFINE_STATIC_LOCAL(const String, notfound, (""));
    return notfound;
}

#if ENABLE(VIDEO_TRACK)
void MediaPlayerPrivate::setTracks()
{
    m_platformMediaPlayer->clearTrack();
    HTMLMediaElement* element = static_cast<HTMLMediaElement*>(m_player->mediaPlayerClient());
    for (Node* node = element->firstChild(); node; node = node->nextSibling()) {
        if (node->hasTagName(HTMLNames::trackTag)) {
            HTMLTrackElement* track = static_cast<HTMLTrackElement*>(node);
            m_platformMediaPlayer->addTrack(track->src().string().utf8().data(), track->srclang().utf8().data());
        }
    }
}
#endif

} // namespace WebCore

#endif // ENABLE(VIDEO)
